package com.melon.common.config.mybatis;

import com.melon.common.persistence.interceptor.PaginationInterceptor;
import com.melon.common.persistence.interceptor.PerformanceInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

/**
 * Mybatis半自动化配置.
 * Author: xjt2016
 * Date: 2016/8/21
 * Time: 18:46
 */
@Configuration
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
//@ConditionalOnBean(DataSource.class)
@EnableConfigurationProperties(MybatisProperties.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
@AutoConfigureBefore(MybatisAutoConfiguration.class)
public class MyBatisConfig {
    private static Logger logger = LoggerFactory.getLogger(MyBatisConfig.class);

    /***
     * 分页插件
     * @return PageHelper
     */
    @Bean
    public Interceptor paginationInterceptor() {
        logger.debug("注册MyBatis分页插件PageHelper");
        /*PageHelper pageHelper = new PageHelper();
        Properties p = new Properties();
        p.setProperty("offsetAsPageNum", "true");
        p.setProperty("rowBoundsWithCount", "true");
        p.setProperty("reasonable", "true");
        pageHelper.setProperties(p);
        return pageHelper;*/
        PaginationInterceptor interceptor = new PaginationInterceptor();
        Properties p = new Properties();
        p.setProperty("dbType", "mysql");
        interceptor.setProperties(p);
        return interceptor;
    }

    /***
     * Mybatis sql查询性能检测
     * @return
     */
    @Bean
    public Interceptor performanceInterceptor() {
        PerformanceInterceptor interceptor = new PerformanceInterceptor();
        return interceptor;
    }

}
